import { createRouter,createWebHashHistory } from "vue-router";
import Layout from '../components/Layout.vue'

const routes=[
    {
        path:'/login',
        component:()=>import('../views/Login.vue'),
        meta:{title:'登录'},
        hidden:true
    },
    {
        path:'/',
        component:Layout,
        meta:{title:'首页'},
        redirect:'/home', //路由重定向
        hidden:true,
        children:[
            {
                path:'home',
                meta:{title:'首页'},
                component:()=>import('../views/Home.vue')
            }
        ]
    },
    {
        path:'/teacher',
        component:Layout,
        meta:{title:'讲师管理',icon:'Avatar'},
        redirect:'/teacher/list',
        children:[
            {
                path:'list',
                meta:{title:'讲师列表'},
                component:()=>import('../views/teacher/list.vue')
            },
            {
                path:'form',
                meta:{title:'添加讲师'},
                component:()=>import('../views/teacher/form.vue')
            }
        ]
    },
    {
        path:'/course',
        component:Layout,
        meta:{title:'课程管理',icon:'Notebook'},
        redirect:'/course/list',
        children:[
            {
                path:'list',
                meta:{title:'课程列表'},
                component:()=>import('../views/course/list.vue')
            },
            {
                path:'form',
                meta:{title:'添加课程'},
                component:()=>import('../views/course/form.vue')
            }
        ]
    }
]

//通过createRouter方法创建路由
const router=createRouter({
    history:createWebHashHistory(),
    routes
})

//全局前置守卫
router.beforeEach((to, from, next) => {
    //若请求的是登陆页面，则放行，否则判断用户是否登录
    //若没有登录，自然跳转到登陆页面
    if (to.path === '/login') {
        next()
    } else {
        //判断用户是否登录(检查localStorage中是否存在token)
        const token = localStorage.getItem('member_token')
        if (token) {
            next()
        } else {
            next('/login')
        }
    }
})

export default router